import json
from functools import wraps

from app.extensions import cache


def cache_func_data(cache_time=600):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, forced_refresh=False, **kwargs):
            # 生成缓存的键

            args_key = ".".join([str(k) for k in args])
            # args_key = ".".join([k.__class__.__name__ if isinstance(k, type) else str(k) for k in args])
            cache_key = "func:{}:{}-{}".format(func.__name__, args_key, json.dumps(kwargs, default=str))
            data = cache.get(cache_key)
            # print(cache_key, bool(data))
            if data and not forced_refresh:
                return data

            data = func(*args, **kwargs)
            cache.set(cache_key, data, expire=cache_time)

            return data

        return wrapper

    return decorator
